package com.zch.socket.aio.client2;

import com.zch.socket.common.ByteUtils;
import com.zch.socket.common.model.RequestModel;
import com.zch.socket.common.model.ResponseModel;

import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class ClientReadHandler implements CompletionHandler<Integer,ByteBuffer> {
    private AsynchronousSocketChannel clientChannel;

    public ClientReadHandler(AsynchronousSocketChannel clientChannel) {
        this.clientChannel = clientChannel;
    }

    @Override
    public void completed(Integer result, ByteBuffer attachment) {
        ResponseModel responseModel= (ResponseModel) ByteUtils.ByteBufferToObject(attachment);
        String result1 =  responseModel.getStr();
        System.out.println("客户端收到服务端返回: "+result1);
        //读完了再写
        ByteBuffer read=ByteBuffer.allocate(1024);
        //clientChannel.write(read,read,new ClientWriterHandler(clientChannel));
    }

    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
       System.out.println("客户端读取异常");
       exc.printStackTrace();
        //出现异常显示的关闭通道，aio的通道是不会主动关闭的，可以理解为可复用的长连接。
        try {
            clientChannel.close();
        } catch (IOException e) {
        }
    }
}
